# -*- coding: utf-8 -*-
import os
import shutil
import sys

reload(sys)
sys.setdefaultencoding("utf-8")


class LocalUtils(object):
    """ 本地工具类 """

    def __init__(self, logger, util):
        self.log = logger
        self.util = util
        self.local_disk_dir = None
        self.local_disk_limit_percent = None

    def set_config(self, local_disk_dir, local_disk_limit_percent):
        self.local_disk_dir = local_disk_dir
        self.local_disk_limit_percent = local_disk_limit_percent

    # 获取本地主机数据磁盘使用
    def local_disk_size(self):
        script = '''df --block-size=KB | awk '$NF=="''' + self.local_disk_dir + '''" {print $2" "$3" "$4" "$5}' '''
        out, _ = self.util.exec_local_shell(script)
        fields = out[0].strip().split(" ")
        total_kb = fields[0].replace("kB", "")
        used_kb = fields[1].replace("kB", "")
        avail_kb = fields[2].replace("kB", "")
        use_percent = fields[3]
        self.log.info("本地{}磁盘占用: total_kb: {}, Used_kb: {}, Available_kb: {}, Used%: {}".format(
            self.local_disk_dir, total_kb, used_kb, avail_kb, use_percent))
        return total_kb, used_kb, avail_kb, use_percent

    # 本地磁盘+表大小校验
    def local_disk_check(self, tab_size, tab_unit):
        total_kb, used_kb, avail_kb, use_percent = self.local_disk_size()
        current_kb = tab_size
        if tab_unit == "M":
            current_kb = float(tab_size) * 1024
        elif tab_unit == "G":
            current_kb = float(tab_size) * 1024 * 1024
        elif tab_unit == "T":
            current_kb = float(tab_size) * 1024 * 1024 * 1024
        if (float(current_kb) + float(used_kb)) >= float(total_kb) * float(self.local_disk_limit_percent):
            self.log.error("本地磁盘占比超过 {}! Current_kb: {}, Total_kb: {}, Used_kb: {}, Available_kb: {}, Used%: {}".format(
                self.local_disk_limit_percent, current_kb, total_kb, used_kb, avail_kb, use_percent))
            return False
        return True

    def touch_file(self, file_path):
        directory = os.path.dirname(file_path)
        if not os.path.exists(directory):
            os.makedirs(directory)
        if not os.path.exists(file_path):
            self.util.exec_local_shell("touch {}".format(file_path))

    def file_size_kb(self, path):
        script = "du -s {}".format(path)
        out, _ = self.util.exec_local_shell(script)
        return out[0].split("\t")[0]

    def make_dirs(self, dir_path):
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

    # 删除目录或文件
    def remove_path(self, path):
        path = path.strip()
        if path == "/" or path == self.local_disk_dir or path == (self.local_disk_dir + "/"):
            self.log.error("删除{}，请核对路径!".format(path))
            return
        if not os.path.exists(path):
            self.log.error("路径不存在请核对! {}".format(path))
            return
        self.log.info("正在删除路径: {}".format(path))
        shutil.rmtree(path)
        self.log.info("已经删除路径: {}".format(path))
